package com.example.casper.Experiment2024.activity;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.example.casper.Experiment2024.R;
import com.example.casper.Experiment2024.adapter.PhotoAdapter;
import com.example.casper.Experiment2024.entity.LocationInfo;
import com.example.casper.Experiment2024.utils.GlideEngine;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PublishActivity extends AppCompatActivity {

    private static final String TAG = "PublishActivity";
    private final List<String> photos = new ArrayList<>();
    private PhotoAdapter adapter;
    private TextView titleText;
    private TextView text;
    private RecyclerView content;
    private View button;
    private LocationInfo locationInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish);
        titleText = findViewById(R.id.titleText);
        text = findViewById(R.id.text);
        content = findViewById(R.id.content);
        button = findViewById(R.id.button);
        adapter = new PhotoAdapter();
        photos.add("-");
        locationInfo = new LocationInfo();

        titleText.setText(getIntent().getStringExtra("title"));

        locationInfo.setLat(getIntent().getDoubleExtra("lat", 0));
        locationInfo.setLon(getIntent().getDoubleExtra("lon", 0));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            requestPermissions(new String[]{Manifest.permission.MANAGE_EXTERNAL_STORAGE}, 0x88);
        } else {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    0x88);
        }

        adapter.setOnItemClickListener((baseQuickAdapter, view, position) -> {
            if (position == photos.size() - 1) {
                PictureSelector.create(PublishActivity.this)
                        .openGallery(SelectMimeType.ofAll())
                        .setMaxSelectNum(6)
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                Log.d(TAG, "onResult() called with: result = [" + result + "]");
                                List<String> list = result.stream().map(LocalMedia::getRealPath).collect(Collectors.toList());
                                photos.addAll(0, list);
                                adapter.submitList(new ArrayList<>(photos));
                            }

                            @Override
                            public void onCancel() {

                            }
                        });

            } else {

            }
        });
        content.setAdapter(adapter);
        adapter.submitList(photos);
        button.setOnClickListener(v -> {
            String titleTextValue = titleText.getText().toString();
            String textValue = text.getText().toString();
            if (TextUtils.isEmpty(titleTextValue) || TextUtils.isEmpty(textValue) || photos.size() <= 1) {
                Toast.makeText(PublishActivity.this, "请添加描述和图片", Toast.LENGTH_SHORT).show();
                return;
            }
            locationInfo.setTitle(titleTextValue);
            locationInfo.setDesc(textValue);
            locationInfo.setImage(adapter.getItems().stream().filter(s -> s.length() > 1).collect(Collectors.toList()));
            SharedPreferences preferences = getSharedPreferences("config", Context.MODE_PRIVATE);
            String json = preferences.getString("points", "[]");
            List<LocationInfo> infos = JSON.parseArray(json, LocationInfo.class);
            if (infos == null) {
                infos = new ArrayList<>();
            }
            infos.add(0,locationInfo);
            preferences.edit().putString("points", JSON.toJSONString(infos)).commit();
            Toast.makeText(this, "发布成功", Toast.LENGTH_SHORT).show();
            finish();
        });
    }
}
